/* eslint-disable semi */
import OSS from 'ali-oss'
import {
  xhrChannels,
  xhrVersions
} from '@/api/analysis'
import {
  mapActions
} from 'vuex';
import DATEPICKER_OPTIONS from '@/config/datepickerOptions';
import { mapFilters } from './mapFilters';
const GlobleMixin = {
  data () {
    return {
      listLoading: false,
      isCheckedStatus: false,
      defaultQueryParams: {
        page: 1,
        limit: 100
      },
      daterangePickerOptions: DATEPICKER_OPTIONS.daterangePickerOptions
    }
  },
  computed: {},
  methods: {
    ...mapActions({
      logout: 'user/logout'
    }),
    ...mapFilters(['imageUrl']),
    daterangeChangedTimestamp () {
      const start = new Date(this.daterangeValue && this.daterangeValue[0])
      this.listQuery.startTime = `${start.getFullYear()}-${start.getMonth() > 8
        ? start.getMonth() + 1
        : '0' + (start.getMonth() + 1)
        }-${start.getDate() > 9 ? start.getDate() : '0' + start.getDate()}`
      // end_time 需要+1天,
      if (!this.daterangeValue || !this.daterangeValue[1]) {
        this.listQuery.endTime = null
      } else {
        const end = new Date(
          new Date(this.daterangeValue && this.daterangeValue[1]).getTime() +
          24 * 60 * 60 * 1000
        )
        this.listQuery.endTime = `${end.getFullYear()}-${end.getMonth() > 8 ? end.getMonth() + 1 : '0' + (end.getMonth() + 1)
          }-${end.getDate() > 9 ? end.getDate() : '0' + end.getDate()}`
      }
    },
    daterangeChanged () {
      if (this.daterangeValue) {
        if (this.daterangeValue[0]) {
          const startTime = this.daterangeValue[0]
          this.listQuery.startTime = /\d{2}:\d{2}$/g.test(startTime)
            ? new Date(startTime).getTime()
            : new Date(startTime + ' 00:00:00').getTime()
        }
        if (this.daterangeValue[1]) {
          const endTime = this.daterangeValue[1]
          this.listQuery.endTime = /\d{2}:\d{2}$/g.test(endTime)
            ? new Date(endTime).getTime()
            : new Date(endTime + ' 23:59:59').getTime()
        }
      } else {
        this.listQuery.startTime = null
        this.listQuery.endTime = null
      }
    },
    handleFilter () {
      this.listLoading = true
      this.listQuery.offset = 0
      this.listQuery.page = 1
      this.doSearch()
    },
    handleCheckedStatus () {
      if (this.listQuery.type === 1) {
        this.isCheckedStatus = true
      } else {
        this.isCheckedStatus = false
      }
    },
    resetFilter () {
      if (this.defaultQueryParams) {
        this.listQuery = Object.assign({}, this.defaultQueryParams)
      } else {
        for (var key in this.listQuery) {
          this.listQuery[key] = null
        }
      }
      this.daterangeValue = ''
      this.doSearch()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.listQuery.pageSize = val
      this.doSearch()
    },
    handleSizeChange2 (val) {
      this.listQuery.limit = val
      this.listQuery.pageSize = val
      this.doSearch2()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.listQuery.pageNum = val
      this.doSearch()
    },
    handleCurrentChange2 (val) {
      this.listQuery.page = val
      this.listQuery.pageNum = val
      this.doSearch2()
    },

    handleCurrentChangeOffset (val) {
      this.listQuery.page = val
      this.listQuery.offset = (this.listQuery.limit || 10) * (val - 1)
      this.doSearch()
    },
    // 上传文件到阿里云服务器
    async uploadFileToAliOss (file) {
      const client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: 'LTAI4G7gKbqrZDkDEw1LXHA5',
        accessKeySecret: 'p1eX4hH7GymRZLfnhkUFMQlU2P7rAt',
        bucket: 'vchat-res'
      })
      const data = file.file

      async function putObject () {
        try {
          // object-key可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
          return await client.put(
            'console/images/' +
            new Date().getTime() +
            '_' +
            data.name.replace(/\.\w+$/, ''),
            data
          )
        } catch (e) {
          console.log(e)
        }
      }
      return putObject()
    },
    xhrGetChannels () {
      return new Promise((resolve, reject) => {
        xhrChannels()
          .then(resp => {
            resolve(resp)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    xhrGetVersions () {
      return new Promise((resolve, reject) => {
        xhrVersions().then(resp => {
          resolve(resp);
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 定义导出Excel表格事件
    exportExcel (option, excelName) {
      const table_data = document.querySelector(option)
      const ths = table_data.querySelector('thead').querySelectorAll('th')
      const header = {}
      for (const th in ths) {
        if (ths[th].colSpan === 1) {
          header[th] = ths[th].innerText
        }
      }
      const trs = table_data.querySelector('tbody').querySelectorAll('tr')
      const data = []
      for (let tr = 0; tr < trs.length; tr++) {
        const tds = trs[tr].querySelectorAll('td')
        const tmp = []
        for (let td = 0; td < tds.length; td++) {
          tmp.push(tds[td].innerText)
        }
        data.push(tmp)
      }
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.values(header), // 表头 必填
          data, // 具体数据 必填
          filename: excelName, // 非必填
          bookType: 'xlsx'
        })
      })
    },
    isNotNullOrEmpty (str) {
      return str != null && str != undefined && str != ""
    },
    JSONParse (str) {
      if (this.isNotNullOrEmpty(str)) {
        return JSON.parse(str)
      }
    },
    isMutiLanguageConfigValid (config) {
      var result = true
      for (const [key, value] of Object.entries(config)) {
        console.log(`Key: ${key}, Value: ${value}`)
        if (!this.isNotNullOrEmpty(value)) {
          result = false
        }
      }
      return result
    },
  }
}
export default GlobleMixin
